<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="">权限管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRoleDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row
                                :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                                v-for="(item1, i1) in scope.row.children"
                                :key="item1.id">
                            <!--一级权限-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--二级权限-->
                            <el-col :span="19">
                                <el-row :class="['bdbottom',i2===0 ?'bdtop' : '','vcenter']"
                                        v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)" >{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!--三级权限-->
                                    <el-col :span="18">
                                        <el-tag  v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>

                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"> </el-table-column>
                <el-table-column prop="roleName" label="角色名称" > </el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
                <el-table-column  label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRoleById(scope.row.id)">删除</el-button>
                        <el-button
                                type="warning"
                                icon="el-icon-setting"
                                size="mini"
                                @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-card>
        <!--添加角色对话框-->
        <el-dialog title="添加角色信息" :visible.sync="addRoleDialogVisible" @close="addDialogClosed()">
            <el-form :model="addRoleForm"
                     ref="addRoleFormRef"
                     :rules="addRoleFormRoles"
                     label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑角色信息" :visible.sync="editRoleDialogVisible" @close="editDialogClosed()">
            <el-form :model="editRoleForm"
                     ref="editRoleFormRef"
                     :rules="editRoleFormRoles"
                     label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="分配权限信息" :visible.sync="setRoleDialogVisible" @close="setRightDialogClosed">
            <el-form label-width="100px">
                <el-tree
                        :data="rightsList"
                        ref="treeRef"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :default-checked-keys="defKeys"
                        :props="treeProps">
                </el-tree>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Roles",
        data(){
            return{
                addRoleForm:{
                    roleName:'',
                    roleDesc:''
                },
                // 角色列表
                rolesList: [],
                //角色 对话框属性
                addRoleDialogVisible:false,
                // 编辑 角色 列表
                editRoleForm:{},
                // 编辑 角色 对话框 属性
                editRoleDialogVisible:false,
                // 分配 角色 对话框属性
                setRoleDialogVisible:false,
                //  树形控件的属性绑定对象
                treeProps: {
                    label: 'authName',
                    children: 'children'
                },
                // 权限 列表
                rightsList:[],
                //   当前即将分配权限的Id
                roleId: 0,
                // 存取 节点 keys
                defKeys:[],
                // 添加 角色 表单校验
                addRoleFormRoles:{
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        {
                            min: 2,
                            max: 10,
                            message: '角色名称的长度在2～10个字',
                            trigger: 'blur'
                        }
                    ],
                    roleDesc: [
                        { required: true, message: '请输入角色描述信息', trigger: 'blur' },
                        {
                            min: 2,
                            max: 10,
                            message: '角色描述信息必须2～10个字',
                            trigger: 'blur'
                        }
                    ]
                },
                // 编辑 角色 表单校验
                editRoleFormRoles:{
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        {
                            min: 2,
                            max: 10,
                            message: '角色名称的长度在2～10个字',
                            trigger: 'blur'
                        }
                    ],
                    roleDesc: [
                        { required: true, message: '请输入角色描述信息', trigger: 'blur' },
                        {
                            min: 2,
                            max: 10,
                            message: '角色描述信息必须2～10个字',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        },
        created() {
            this.getRoleList()
        },
        methods:{
            // 获取角色 列表
            async getRoleList(){
                const {data:res} = await this.$http.get('roles')
                //console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败!')
                }
                this.rolesList = res.data
            },
            // 监听 添加角色 对话框 关闭事件
            addDialogClosed(){
                // 重置表单
                this.$refs.addRoleFormRef.resetFields()
            },
            // 监听 添加角色 对话框 关闭事件
            editDialogClosed(){
                // 重置表单
                this.$refs.editRoleFormRef.resetFields()
            },
            // 添加 角色 事件
            async addRole(){
                this.$refs.addRoleFormRef.validate(async valid=>{
                    if (!valid) return
                    const {data:res} = await this.$http.post('roles',this.addRoleForm)
                    if (res.meta.status !== 201){
                        return this.$message.error('添加角色失败!')
                    }
                    this.$message.success('添加角色信息成功!')
                    this.addRoleDialogVisible = false
                    // 刷新 角色 列表
                    this.getRoleList()
                })

            },
            // 编辑 角色 信息
            showEditDialog(id){
                this.editRoleDialogVisible = true
                this.$http.get('roles/' + id).then(res=>{
                    if (res.data.meta.status !== 200) return this.$message.error('查询角色信息失败！')
                    this.editRoleForm = res.data.data
                    this.editRoleDialogVisible = true
                })
            },
            editRole(){
                this.$refs.editRoleFormRef.validate(valid =>{
                    // 表单 校验失败
                    if (!valid) return
                    this.$http.put(
                        'roles/' + this.editRoleForm.roleId,
                        {
                            roleName: this.editRoleForm.roleName,
                            roleDesc: this.editRoleForm.roleDesc
                        }).then(res=>{
                            if (res.data.meta.status !== 200) {
                                this.$message.error('更新角色信息失败！')
                            }
                            // 隐藏编辑角色对话框
                            this.editRoleDialogVisible = false
                            this.$message.success('更新角色信息成功！')
                            this.getRoleList()
                    }).catch(err =>{
                        console.log(err);
                    })

                })

            },
            // 删除 角色 信息
            async delRoleById(id){
               // console.log('删除角色信息'+id);
                await this.$confirm(
                    '是否删除此角色信息?',
                    '提示',
                    {
                        confirmButtonText:'删除',
                        cancelButtonText:'取消',
                        type:'warning'
                    }
                ).then(res=>{
                    // console.log(res)
                    if (res !=='confirm'){
                        return this.$message.success('已取消删除操作!')
                    }
                    //console.log(this.$http.delete('roles/' + id));
                    this.$http.delete('roles/' + id).then(res =>{
                        //console.log(res);
                        if (res.data.meta.status !== 200) return this.$message.error('删除角色失败！')
                        this.$message.success('删除用户成功！')

                    }).catch(err=>{
                        console.log(err)
                    })

                }).catch(err=>{
                    console.log(err)
                })
                await this.getRoleList()

            },
            // 分配 角色  信息
            async showSetRightDialog(role){
                //console.log('分配角色信息'+role);
                this.roleId = role.id
                await this.$http.get('rights/tree').then(res =>{
                    if (res.data.meta.status !== 200) {
                        return this.$message.error('获取权限数据失败！')
                    }
                    //   获取权限树
                    this.rightsList = res.data.data
                    // 递归 获取 三级节点的id
                    this.getLeafKeys(role,this.defKeys)
                }).catch(err=>{
                    console.log(err);
                })

                this.setRoleDialogVisible = true
            },
            // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
            getLeafKeys(node,arr){
                // 没有children 节点，则是 三级节点
                if (!node.children){
                    return arr.push(node.id)
                }
                //存在 子节点
                node.children.forEach(item =>{
                    this.getLeafKeys(item,arr)
                })
            },
            // 保存 当前 权限
            async allotRights(roleId){
                // 获取 当前 选中和半选中的id
                const keys=[
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]
                const idStr = keys.join(',');
                await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr}).then(res=>{
                    if (res.data.meta.status !== 200) { return this.$message.error('分配权限失败！') }
                    this.$message.success('分配权限成功!')
                }).catch(err=>{
                    console.log(err);
                })
                this.setRoleDialogVisible = false
            },
            // 权限对话框关闭事件
            setRightDialogClosed () {
                this.rightsList = []
            },
            async removeRightById(role,id){
                //console.log('删除id:'+row+",id:"+id)
                await this.$confirm(
                    '是否删除此权限?',
                    '提示',
                    {
                        confirmButtonText:'确定',
                        cancelButtonText:'取消',
                        type:'warning'
                    }
                ).then(res=>{
                    //console.log(res)
                        this.$http.delete(
                            `roles/${role.id}/rights/${id}`
                        ).then(res=>{
                            if (res.data.meta.status !== 200) {
                                return this.$message.error('删除权限失败！')
                            }
                            this.$message.success('删除成功!')
                            this.rolesList = res.data.data
                            //   不建议使用
                            this.getRoleList()
                        })
                }).catch(err=>{
                    this.$message.error('已取消删除操作!')
                })
            }
        }
    }
</script>

<style type="less" scoped>
    .el-tag {
        margin: 7px;
    }
    .bdtop {
        border-top: 1px solid #eee;
    }
    .bdbottom {
        border-bottom: 1px solid #eee;
    }
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>